package com.nova.bluetooth.ui.ai;

import static com.nova.bluetooth.base.CommonMessageWrap.ACTION_AIUI_TTS_RESULT;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.iflytek.aiui.AIUIConstant;
import com.iflytek.aiui.AIUIEvent;
import com.nova.bluetooth.MyApp;
import com.nova.bluetooth.R;
import com.nova.bluetooth.base.BaseFragment;
import com.nova.bluetooth.base.CommonMessageWrap;
import com.nova.bluetooth.databinding.FragmentTtsRobotBinding;
import com.nova.bluetooth.helpUtils.EventBusUtil;
import com.nova.bluetooth.helpUtils.LogUtil;
import com.nova.bluetooth.helpUtils.StorageUtil;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.manage.AiUiManager;
import com.nova.bluetooth.xunFeiSDK.utils.FileUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

/**
 * 语音合成
 */
public class TTSRobotFragment extends BaseFragment {
    private FragmentTtsRobotBinding binding;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetMessage(CommonMessageWrap event) {
        if (event.getEventCode() == ACTION_AIUI_TTS_RESULT) {
//            AIUIEvent aiuiEvent = (AIUIEvent) event.getObject();
//            dealWithAiuiEvent(aiuiEvent);
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBusUtil.register(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tts_robot, container, false);
        binding = FragmentTtsRobotBinding.bind(view);
        initData();
        initView();
        return binding.getRoot();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        AiUiManager.getInstance().destroyAiUiAllEngine();
        EventBusUtil.unRegister(this);
    }

    private void initView() {
        binding.btnConfirm.setOnClickListener(onClickEvent);
        binding.ivBack.setOnClickListener(onClickEvent);
        binding.lauoutTts1.setOnClickListener(onClickEvent);
        binding.lauoutTts2.setOnClickListener(onClickEvent);
        binding.lauoutTts3.setOnClickListener(onClickEvent);
        binding.lauoutTts4.setOnClickListener(onClickEvent);
        binding.lauoutTts1.setSelected(true);
        binding.lauoutTts2.setSelected(false);
        binding.lauoutTts3.setSelected(false);
        binding.lauoutTts4.setSelected(false);
    }

    private void initData(){
        AiUiManager.getInstance().initAiUi(MyApp.getInstance());
        AiUiManager.TTS_ROBOT = AiUiManager.TTS_ROBOT_PERSON1;
    }

    String filePath = StorageUtil.getTTSDir();
    File file = null;
    private int mUIPercent;
    private String mTitle;

    private void dealWithAiuiEvent(AIUIEvent event) {
        LogUtil.d("dealWithAiuiEvent TTS 播放完毕");
        if (event.eventType == AIUIConstant.EVENT_RESULT) {
            try {
                JSONObject bizParamJson = new JSONObject(event.info);
                JSONObject data = bizParamJson.getJSONArray("data").getJSONObject(0);
                JSONObject params = data.getJSONObject("params");
                JSONObject content = data.getJSONArray("content").getJSONObject(0);

                LogUtil.d("test==>params:" + params.toString());

                String sub = params.optString("sub");
                if ("tts".equals(sub)) {
                    if (content.has("cnt_id")) {

                        String sid = event.data.getString("sid");
                        String cnt_id = content.getString("cnt_id");
                        byte[] audio = event.data.getByteArray(cnt_id); //合成音频数据
                        /**
                         *
                         * dts：音频块进度信息，取值：
                         * - 0（音频开始）
                         * - 1（音频中间块，可出现多次）
                         * - 2（音频结束)
                         * - 3（独立音频,合成短文本时出现）
                         *
                         * 举例说明：
                         * 常规合成dts顺序：
                         *   0 1 1 1 ... 2
                         * 短文本合成dts顺序:
                         *   3
                         **/
                        int dts = content.getInt("dts");
                        int percent = event.data.getInt("percent"); //合成进度

                        int text_percent = 0;
                        try {
                            text_percent = content.getInt("text_percent");
                        } catch (JSONException e) {
                            LogUtil.e(e.toString());
                        }

                        // TODO: 2024/12/7 优化用户体验UI
                        if (percent != 0) {
                            mUIPercent = percent;
                        } else if (text_percent != 0) {
                            mUIPercent = text_percent;
                        }else {
                            mUIPercent++;
                        }

                        boolean isCancel = false;  //合成过程中是否被取消
                        try {
                            isCancel = "1".equals(content.getString("cancel"));
                        } catch (JSONException e) {
                            LogUtil.e(e.toString());
                        }
                        LogUtil.d("合成进度 mUIPercent：" + mUIPercent + " percent:" + percent + " dts:" + dts + " 合成过程中是否被取消:" + isCancel + " data:" + event.data.toString());

//                        将合成音频保存到SD卡/可以 dts=2时，将文件上传服务端
//                        String dateStr = DateUtil.getDateToString(System.currentTimeMillis()
//                                , "yyyy_MM_dd_HH_mm_ss");
                        String name = mTitle + ".pcm";
                        if (dts == 0) {
                            file = new File(filePath, name);//创建文件，第一个参数为路径，第二个参数为文件名
                            if (file.exists()) {
                                file.delete();
                            }
                        }
                        if (file != null) {
                            FileUtil.writeFile(audio, file.getPath()); //保存文件
                        }

//                        if (dialogTTSSubmit != null) {
//                            dialogTTSSubmit.setProgress(mUIPercent);
//                            if (dts == 2) {
//                                if (!isSubmit) {
//                                    return;
//                                }
//                                String newFilePath =
//                                        file.getParentFile().getAbsolutePath() + "/" + mTitle;
//                                ConvertUtils.convertPcm2Wav(file.getAbsolutePath(), newFilePath);
//                                File newFile = new File(newFilePath + ".wav");
//                                long duration = AudioDurationUtils.getAudioDuration(newFile.getAbsolutePath());
//                                KLog.d("test==>newFile = " + newFile.getAbsolutePath() + " duration:" + duration);
//                                int audioTime = 0;
//                                try {
//                                    audioTime = Math.toIntExact(duration / 1000);
//                                    // 继续处理 audioTime
//                                } catch (ArithmeticException e) {
//                                    KLog.e("Duration is too large to fit in an int: " + duration);
//                                }
//                                uploadAudio(newFile, mTitle + ".wav", audioTime,new UploadCallback() {
//                                    @Override
//                                    public void onSuccess(String s) {
//                                        super.onSuccess(s);
//                                        dialogTTSSubmit.setProgress(100);
//
//                                        isSubmit = false;
//                                        boolean delete = file.delete();
//                                        KLog.d(delete + "删除:" + newFile.getAbsolutePath());
//                                        new Handler().postDelayed(() -> {
//                                            UploadRepository.getInstance().removeCallback();
//                                            ToastUtils.show(getString(com.sanag.common.R.string.ai_ftf_20));
//                                            dialogTTSSubmit.dismissDialog();
//                                            TTSContentActivityCopy.startTtsContentActivity(TTSRobotActivity.this);
//                                            finish();
//                                        }, 500);
//
//                                    }
//
//                                    @Override
//                                    public void onFail(String errCode) {
//                                        super.onFail(errCode);
//                                        ToastUtils.show(TTSRobotActivity.this, errCode);
//                                        dialogTTSSubmit.dismissDialog();
//                                        UploadRepository.getInstance().removeCallback();
//                                        isSubmit = false;
//                                    }
//                                });

//                            }
//                        }
//
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
            }
        } else if (event.eventType == AIUIConstant.CMD_STOP_SAVE) {
            if (event.arg1 == 5) { //语音合成完毕
                AiUiManager.TTSIsStart = false;
                LogUtil.d("TTS 播放完毕");
            }
        }
    }


    private void stopTTS() {
        AiUiManager.getInstance().stopTTS();
    }

    private void startTTS(String str) {
        AiUiManager.getInstance().startTTSBySdk(str);
    }


    private void updateTTSRobotUI(View view) {
        binding.lauoutTts1.setSelected(false);
        binding.lauoutTts2.setSelected(false);
        binding.lauoutTts3.setSelected(false);
        binding.lauoutTts4.setSelected(false);
        if (view.getId() == R.id.lauout_tts_1){
            binding.lauoutTts1.setSelected(true);
            AiUiManager.TTS_ROBOT = AiUiManager.TTS_ROBOT_PERSON1;
        }else if (view.getId() == R.id.lauout_tts_2){
            binding.lauoutTts2.setSelected(true);
            AiUiManager.TTS_ROBOT = AiUiManager.TTS_ROBOT_PERSON2;
        }else if (view.getId() == R.id.lauout_tts_3){
            binding.lauoutTts3.setSelected(true);
            AiUiManager.TTS_ROBOT = AiUiManager.TTS_ROBOT_PERSON3;
        }else if (view.getId() == R.id.lauout_tts_4){
            binding.lauoutTts4.setSelected(true);
            AiUiManager.TTS_ROBOT = AiUiManager.TTS_ROBOT_PERSON4;
        }

        String hello = "您好啊，今天过得好吗";
        AiUiManager.getInstance().startTTSBySdk(hello);
    }
    private final View.OnClickListener onClickEvent = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.btn_confirm){
                String mStr = binding.etInput.getText().toString();
                if (mStr.isEmpty()){
                    ToastUtils.show("请输入内容");
                    return;
                }else {
                    startTTS(mStr);
                }
            }else if (v.getId() == R.id.iv_back){
                getActivity().finish();
            }else if (v.getId() == R.id.lauout_tts_1 || v.getId() == R.id.lauout_tts_2 || v.getId() == R.id.lauout_tts_3 || v.getId() == R.id.lauout_tts_4){
                updateTTSRobotUI(v);
            }
        }
    };
}
